import requests
import ipaddress

def check_ip_location(ip):
    url = f"http://ip-api.com/json/{ip}"  # IP地址归属地查询API的URL
    response = requests.get(url)
    data = response.json()
    country = data["country"]
    region = data["regionName"]
    city = data["city"]
    isp = data["isp"]

    return f"{country} {region} {city} {isp}"

def convert_subnet_to_hosts(subnet):
    network = ipaddress.ip_network(subnet)
    hosts = [str(ip) for ip in network.hosts()]
    return hosts

# 读取源文件
filename = "VLSM.txt"
output_filename = "HOST_with_info.txt"
all_hosts_with_info = set()  # 使用集合去除重复的IP地址

with open(filename, "r") as file:
    subnets = file.read().split(",")

# 转换为可用主机地址并进行去重
for subnet in subnets:
    subnet = subnet.strip()
    hosts = convert_subnet_to_hosts(subnet)
    all_hosts_with_info.update(hosts)  # 使用update方法将新的主机地址添加到集合中，自动去重

# 将主机地址排序
sorted_hosts = sorted(all_hosts_with_info, key=lambda x: ipaddress.ip_address(x))

# 查询并写入目标文件
with open(output_filename, "w", encoding='utf-8') as file:
    for host in sorted_hosts:
        info = check_ip_location(host)
        host_with_info = f"{host} #{info}"  # 在IP地址后面添加#country regionName city isp
        file.write(host_with_info + "\n")

print("转换完成，结果已写入 HOST_with_info.txt 文件。")